<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <i class="el-icon-document stat-icon" style="color: #409EFF;" />
            <div class="stat-content">
              <div class="stat-value">{{ stats.total }}</div>
              <div class="stat-label">总提交数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <i class="el-icon-warning stat-icon" style="color: #E6A23C;" />
            <div class="stat-content">
              <div class="stat-value">{{ stats.pending_count }}</div>
              <div class="stat-label">待审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <i class="el-icon-delete stat-icon" style="color: #F56C6C;" />
            <div class="stat-content">
              <div class="stat-value">{{ stats.spam_count }}</div>
              <div class="stat-label">垃圾信息</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <i class="el-icon-pie-chart stat-icon" style="color: #67C23A;" />
            <div class="stat-content">
              <div class="stat-value">{{ spamRate }}%</div>
              <div class="stat-label">垃圾率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选栏 -->
    <el-card shadow="never" style="margin-bottom: 20px;">
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item label="网站">
          <el-select
            v-model="listQuery.website_id"
            placeholder="所有网站"
            clearable
            style="width: 200px;"
          >
            <el-option
              v-for="site in websites"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="表单类型">
          <el-select
            v-model="listQuery.form_type"
            placeholder="所有类型"
            clearable
            style="width: 150px;"
          >
            <el-option label="联系表单" value="contact" />
            <el-option label="询价表单" value="quote" />
            <el-option label="订阅表单" value="subscribe" />
            <el-option label="咨询表单" value="inquiry" />
            <el-option label="反馈表单" value="feedback" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="listQuery.status"
            placeholder="所有状态"
            clearable
            style="width: 150px;"
          >
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="垃圾信息" value="spam" />
            <el-option label="已处理" value="processed" />
            <el-option label="已归档" value="archived" />
          </el-select>
        </el-form-item>

        <el-form-item label="搜索">
          <el-input
            v-model="listQuery.search"
            placeholder="邮箱/IP/内容"
            clearable
            style="width: 200px;"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="loadData">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          <el-button
            v-if="multipleSelection.length > 0"
            type="success"
            icon="el-icon-check"
            @click="handleBatchApprove"
          >
            批量通过
          </el-button>
          <el-button
            v-if="multipleSelection.length > 0"
            type="danger"
            icon="el-icon-delete"
            @click="handleBatchSpam"
          >
            标记垃圾
          </el-button>
          <el-button
            type="warning"
            icon="el-icon-download"
            @click="handleExport"
          >
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="ID" width="80" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="网站/域名" min-width="180">
        <template slot-scope="{row}">
          <div style="font-size: 13px;">
            <div style="font-weight: 500;">{{ row.website_name }}</div>
            <div style="color: #999; font-size: 12px;">{{ row.domain }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="类型" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag size="mini" :type="getFormTypeColor(row.form_type)">
            {{ getFormTypeText(row.form_type) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="联系信息" min-width="200">
        <template slot-scope="{row}">
          <div style="font-size: 12px;">
            <div v-if="row.name">
              <i class="el-icon-user" /> {{ row.name }}
            </div>
            <div v-if="row.email" style="color: #409EFF;">
              <i class="el-icon-message" /> {{ row.email }}
            </div>
            <div v-if="!row.name && !row.email" style="color: #999;">
              暂无联系信息
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="120" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(row.status)" size="small">
            {{ getStatusText(row.status) }}
          </el-tag>
          <div v-if="row.spam_score > 0" style="font-size: 11px; color: #F56C6C; margin-top: 4px;">
            风险: {{ row.spam_score }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="IP地址" width="130" align="center">
        <template slot-scope="{row}">
          <span style="font-size: 12px;">{{ row.ip_address }}</span>
        </template>
      </el-table-column>

      <el-table-column label="提交时间" width="160" align="center">
        <template slot-scope="{row}">
          <div style="font-size: 12px;">
            <div>{{ row.created_at.split(' ')[0] }}</div>
            <div style="color: #999;">{{ row.created_at.split(' ')[1] }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleView(row)">
            查看
          </el-button>
          <el-dropdown style="margin-left: 10px;" @command="(cmd) => handleCommand(cmd, row)">
            <el-button size="mini">
              更多<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="approve" icon="el-icon-check">
                标记通过
              </el-dropdown-item>
              <el-dropdown-item command="spam" icon="el-icon-warning">
                标记垃圾
              </el-dropdown-item>
              <el-dropdown-item command="processed" icon="el-icon-finished">
                标记已处理
              </el-dropdown-item>
              <el-dropdown-item command="delete" icon="el-icon-delete" divided>
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total>0"
      :current-page.sync="listQuery.page"
      :page-sizes="[10, 20, 30, 50]"
      :page-size.sync="listQuery.limit"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right;"
      @size-change="loadData"
      @current-change="loadData"
    />

    <!-- 详情对话框 -->
    <el-dialog
      :title="`表单详情 #${currentRow.id}`"
      :visible.sync="dialogVisible"
      width="800px"
    >
      <div v-if="currentRow.id" class="detail-container">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="网站">
            {{ currentRow.website_name }}
          </el-descriptions-item>
          <el-descriptions-item label="域名">
            {{ currentRow.domain }}
          </el-descriptions-item>
          <el-descriptions-item label="表单类型">
            <el-tag size="small">{{ getFormTypeText(currentRow.form_type) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRow.status)">
              {{ getStatusText(currentRow.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ currentRow.ip_address }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ currentRow.created_at }}
          </el-descriptions-item>
          <el-descriptions-item label="垃圾评分">
            <el-tag :type="currentRow.spam_score >= 60 ? 'danger' : 'success'" size="small">
              {{ currentRow.spam_score }} / 100
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交耗时">
            {{ currentRow.submission_time }}秒
          </el-descriptions-item>
          <el-descriptions-item v-if="currentRow.page_url" label="页面URL" :span="2">
            <a :href="currentRow.page_url" target="_blank">{{ currentRow.page_url }}</a>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentRow.spam_reason" label="风险原因" :span="2">
            <el-alert :title="currentRow.spam_reason" type="warning" :closable="false" />
          </el-descriptions-item>
        </el-descriptions>

        <!-- 表单数据 -->
        <div style="margin-top: 20px;">
          <h4>📋 表单数据</h4>
          <el-card shadow="never" style="background: #f5f7fa;">
            <div v-if="currentRow.form_data && Object.keys(currentRow.form_data).length > 0">
              <div v-for="(value, key) in currentRow.form_data" :key="key" style="margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #e4e7ed;">
                <div style="color: #909399; font-size: 12px; margin-bottom: 4px;">{{ key }}</div>
                <div style="color: #303133; font-size: 14px; word-break: break-word;">{{ value }}</div>
              </div>
            </div>
            <div v-else style="color: #909399; font-size: 13px; text-align: center; padding: 20px;">
              暂无表单数据
            </div>
          </el-card>
        </div>

        <!-- 备注 -->
        <div style="margin-top: 20px;">
          <h4>📝 备注</h4>
          <el-input
            v-model="currentRow.notes"
            type="textarea"
            :rows="3"
            placeholder="添加备注信息..."
          />
        </div>

        <!-- User Agent -->
        <div v-if="currentRow.user_agent" style="margin-top: 20px;">
          <h4>🖥️ User Agent</h4>
          <el-card shadow="never" style="background: #f5f7fa;">
            <span style="font-size: 12px; color: #666;">{{ currentRow.user_agent }}</span>
          </el-card>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存备注</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { List, Get, Put, Delete, GetStats, BatchUpdate, ExportData } from '@/api/static_web_form_submission'
import { Get as GetWebsites } from '@/api/static_web/website'

export default {
  name: 'FormSubmissions',
  components: {},
  data() {
    return {
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        website_id: '',
        form_type: '',
        status: '',
        search: ''
      },
      stats: {
        total: 0,
        pending_count: 0,
        spam_count: 0
      },
      websites: [],
      multipleSelection: [],
      dialogVisible: false,
      currentRow: {}
    }
  },
  computed: {
    spamRate() {
      if (this.stats.total === 0) return 0
      return ((this.stats.spam_count / this.stats.total) * 100).toFixed(1)
    }
  },
  created() {
    this.loadWebsites()
    this.loadStats()
    this.loadData()
  },
  methods: {
    async loadWebsites() {
      try {
        const res = await GetWebsites()
        this.websites = res.data || []
      } catch (err) {
        console.error('加载网站列表失败', err)
      }
    },
    async loadStats() {
      try {
        const res = await GetStats()
        this.stats = res.data
      } catch (err) {
        console.error('加载统计数据失败', err)
      }
    },
    async loadData() {
      this.listLoading = true
      try {
        const res = await List(this.listQuery)
        this.list = res.data
        this.total = res.total
      } catch (err) {
        this.$message.error('加载数据失败')
      } finally {
        this.listLoading = false
      }
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        limit: 20,
        website_id: '',
        form_type: '',
        status: '',
        search: ''
      }
      this.loadData()
    },
    async handleView(row) {
      try {
        const res = await Get(row.id)
        this.currentRow = res.data
        this.dialogVisible = true
      } catch (err) {
        this.$message.error('加载详情失败')
      }
    },
    async handleSave() {
      try {
        await Put(this.currentRow.id, {
          notes: this.currentRow.notes
        })
        this.$message.success('保存成功')
        this.dialogVisible = false
        this.loadData()
      } catch (err) {
        this.$message.error('保存失败')
      }
    },
    handleCommand(command, row) {
      if (command === 'delete') {
        this.handleDelete(row)
      } else {
        this.handleUpdateStatus(row, command)
      }
    },
    async handleUpdateStatus(row, status) {
      try {
        await Put(row.id, { status })
        this.$message.success('更新成功')
        this.loadData()
        this.loadStats()
      } catch (err) {
        this.$message.error('更新失败')
      }
    },
    handleDelete(row) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        type: 'warning'
      }).then(async() => {
        try {
          await Delete(row.id)
          this.$message.success('删除成功')
          this.loadData()
          this.loadStats()
        } catch (err) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async handleBatchApprove() {
      const ids = this.multipleSelection.map(item => item.id)
      try {
        await BatchUpdate({ ids, status: 'approved' })
        this.$message.success('批量更新成功')
        this.loadData()
        this.loadStats()
      } catch (err) {
        this.$message.error('批量更新失败')
      }
    },
    async handleBatchSpam() {
      const ids = this.multipleSelection.map(item => item.id)
      try {
        await BatchUpdate({ ids, status: 'spam' })
        this.$message.success('批量标记成功')
        this.loadData()
        this.loadStats()
      } catch (err) {
        this.$message.error('批量标记失败')
      }
    },
    async handleExport() {
      try {
        const res = await ExportData(this.listQuery)
        const blob = new Blob([res], { type: 'text/csv' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = `form_submissions_${Date.now()}.csv`
        link.click()
        this.$message.success('导出成功')
      } catch (err) {
        this.$message.error('导出失败')
      }
    },
    getStatusType(status) {
      const map = {
        'pending': 'warning',
        'approved': 'success',
        'spam': 'danger',
        'processed': 'info',
        'archived': ''
      }
      return map[status] || ''
    },
    getStatusText(status) {
      const map = {
        'pending': '待审核',
        'approved': '已通过',
        'spam': '垃圾',
        'processed': '已处理',
        'archived': '已归档'
      }
      return map[status] || status
    },
    getFormTypeColor(type) {
      const map = {
        'contact': 'primary',
        'quote': 'success',
        'subscribe': 'warning',
        'inquiry': 'info',
        'feedback': ''
      }
      return map[type] || ''
    },
    getFormTypeText(type) {
      const map = {
        'contact': '联系',
        'quote': '询价',
        'subscribe': '订阅',
        'inquiry': '咨询',
        'feedback': '反馈'
      }
      return map[type] || type
    }
  }
}
</script>

<style scoped>
.stat-card {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 40px;
  margin-right: 20px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #999;
  margin-top: 5px;
}

.detail-container h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #333;
}
</style>
